package cn.yuznu.www;

import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class ChatServer extends Frame {
    TextArea ta = new TextArea();
    private ServerSocket server = null;
    private Collection<ClientConn> clients = new ArrayList<>();
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/ChatDB";
    private static final String USER = "root";
    private static final String PASS = "1538389602"; // 替换为你的数据库密码

    public void launchFrame() {
        add(ta, BorderLayout.CENTER);
        setBounds(500, 300, 200, 300);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }

    public ChatServer(int port) throws Exception {
        server = new ServerSocket(port);
        launchFrame();
        startServer();
    }

    public void startServer() throws Exception {
        while (true) {
            Socket socket = server.accept();
            ClientConn client = new ClientConn(socket);
            clients.add(client);
            ta.append("新客户端连接：" + socket.getInetAddress() + ":" + socket.getPort());
            ta.append("\n" + "客户端数量: " + clients.size() + "\n\n");
        }
    }

    class ClientConn implements Runnable {
        private Socket socket;
        private DataInputStream dis;
        private DataOutputStream dos;
        private String username;

        public ClientConn(Socket socket) {
            this.socket = socket;
            try {
                dis = new DataInputStream(socket.getInputStream());
                dos = new DataOutputStream(socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            new Thread(this).start();
        }

        public void run() {
            try {
                String command = dis.readUTF();
                if ("REGISTER".equals(command)) {
                    String username = dis.readUTF();
                    String password = dis.readUTF();
                    register(username, password);
                } else if ("LOGIN".equals(command)) {
                    String username = dis.readUTF();
                    String password = dis.readUTF();
                    if (login(username, password)) {
                        dos.writeUTF("LOGIN_SUCCESS");
                        this.username = username;
                    } else {
                        dos.writeUTF("LOGIN_FAILURE");
                    }
                }
                String message;
                while ((message = dis.readUTF()) != null) {
                    for (ClientConn client : clients) {
                        if (client != this) {
                            client.dos.writeUTF(this.username + ": " + message);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                clients.remove(this);
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ta.append("客户端断开连接\n");
            }
        }

        private boolean login(String username, String password) {
            String sql = "SELECT * FROM Users WHERE username = ? AND password = ?";
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, username);
                pstmt.setString(2, password);

                ResultSet resultSet = pstmt.executeQuery();
                return resultSet.next();
            } catch (SQLException e) {
                System.out.println("登录时SQL异常：" + e.getMessage());
                e.printStackTrace();
                return false;
            }
        }

        private void register(String username, String password) throws IOException {
            String sql = "INSERT INTO Users (username, password) VALUES (?, ?)";
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, username);
                pstmt.setString(2, password);

                int affectedRows = pstmt.executeUpdate();
                if (affectedRows > 0) {
                    dos.writeUTF("REGISTER_SUCCESS");
                } else {
                    dos.writeUTF("REGISTER_FAILURE");
                }
            } catch (SQLException e) {
                System.out.println("注册时SQL异常：" + e.getMessage());
                e.printStackTrace();
                try {
                    dos.writeUTF("REGISTER_FAILURE");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ChatServer cs = new ChatServer(8888);
    }
}